package com.jxc.interceptor;

import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.jxc.aop.LogRef;
import com.jxc.model.po.OperationLog;
import com.jxc.model.po.User;
import com.jxc.model.vo.SessionInfo;
import com.jxc.service.OperationLogServiceI;
import com.jxc.util.Application;
import com.jxc.util.ResourceUtil;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class LoggerInterceptor extends AbstractInterceptor {
	private static final long serialVersionUID = -8150513637987193039L;
	protected transient final Log log = LogFactory.getLog(getClass());

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		String actionClassName = invocation.getAction().getClass().getName();
		String method = invocation.getProxy().getMethod();
		OperationLog operationLog = new OperationLog();

		Date startTime = new Date();
		String result = invocation.invoke();
		Date endTime = new Date();
		for (LogRef logRef : Application.getInstance().getLogRefs()) {
			if (logRef.getMethodName().equals(method)
					&& actionClassName.startsWith(logRef.getClassName())) {
				OperationLogServiceI operationLogService = (OperationLogServiceI) Application
				.getInstance().getApplicationContext().getBean(
						"operationService");
				SessionInfo sessionInfo = (SessionInfo) ServletActionContext
				.getRequest().getSession().getAttribute(
						ResourceUtil.getSessionInfoName());
				Long userId = sessionInfo.getUserId();
				if(userId!=null){
					User user = new User ();
					user.setId(userId);
					operationLog.setUser(user);
				}
				operationLog.setActionName(actionClassName);
				operationLog.setMethod(method);
				operationLog.setOptTime(startTime);
				operationLog.setCostTime(endTime.getTime()
						- startTime.getTime());
				operationLog.setOptIp(getIpAddr());
				operationLog.setInfo(logRef.getInfo());
				
				String params = "";
				Map map = invocation.getInvocationContext().getParameters();
				Set objects = map.entrySet();
				Iterator<Entry<String, Object>> it = objects.iterator();
				while(it.hasNext()){
					Entry<String, Object> entry = it.next();
					if(!entry.getKey().equals("password")){
						if(entry.getValue() instanceof String[]){
							String[] values = (String[])entry.getValue();
							params = params + entry.getKey()+"="+getStrings(values)+";";
						}
					}
					
				}
				operationLog.setParams(params);
				operationLogService.save(operationLog);
				break;
			}
		}
		return result;
	}
	private String getStrings(String[] args){
		String strs = "";
		for(String str:args){
			strs = strs+str+",";
		}
		return strs;
	}
	
	private String getIpAddr() {
		String ip = ServletActionContext.getRequest().getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = ServletActionContext.getRequest().getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = ServletActionContext.getRequest().getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = ServletActionContext.getRequest().getRemoteAddr();
        }
        return ip;
	}
}
